
/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 小峰
 * Date: 2019-10-24
 * Time: 15:06
 */
public class LinkedList<T> extends AbstracList<T> {

    private Node<T> first;

    private static class Node<T> {
        T element;
        Node<T> next;

        public Node(T element, Node<T> next) {
            this.element = element;
            this.next = next;
        }
    }

    @Override
    public void clear() {
        size = 0;
        first = null;
    }

    @Override
    public T get(int index) {
       return getNodeByIndex(index).element;
    }

    @Override
    public T set(int index, T element) {
        Node<T> nodeByIndex = getNodeByIndex(index);
        T element1 = nodeByIndex.element;
        nodeByIndex.element=element;
        return element1;
    }

    @Override
    public void add(int index, T element) {

        if(index==0){
            first=new Node<>(element,first);
        }  else{
            Node<T> nodeByIndex = getNodeByIndex(index-1);
            nodeByIndex.next=  new Node<T>(element,nodeByIndex.next);
        }
        size++;
    }

    @Override
    public T remove(int index) {

        Node<T> curNode=first;
        if(index==0){
             first=curNode.next;
        } else{
            curNode=getNodeByIndex(index);
            getNodeByIndex(index-1).next=getNodeByIndex(index+1);
        }
        size--;
        return curNode.element;
    }

    @Override
    public int indexOf(T element) {
        Node<T> node=first;
        if(element==null){
            for (int i = 0; i < size; i++) {
                   if(node.element==null){
                       return i;
                   }
                node=node.next;
            }
        }  else{
            for (int i = 0; i < size; i++) {
                if(element.equals(node.element)){
                    return i;
                }
                node=node.next;
            }
        }
        return List.ELEMENT_NOT_FOUND;
    }


    /**
     * 根据 index 获取相应的Node信息
     * @param index
     * @return
     */
    private Node<T> getNodeByIndex(int index){
        rangeCheck(index);
        Node<T> myNode=first;
        for (int i = 0; i < index; i++) {
             myNode=myNode.next;
        }
        return myNode;
    }


    @Override
    public String toString() {
        StringBuilder string = new StringBuilder();
        string.append("size=").append(size).append(", [");
        Node<T> node = first;
        for (int i = 0; i < size; i++) {
            if (i != 0) {
                string.append(", ");
            }
            string.append(node);
            node = node.next;
        }
        string.append("]");
        return string.toString();
    }
}
